package com.leyou.sh.trade.service.impl;

import com.leyou.sh.auth.utils.UserContext;
import com.leyou.sh.trade.entity.CartsItem;
import com.leyou.sh.trade.repository.CartsRepository;
import com.leyou.sh.trade.service.CartItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author balisong_fcs
 * @date 2021/1/16 18:30
 * @desc
 */
@Service
public class CartItemServiceImpl implements CartItemService {
    
    @Autowired
    private CartsRepository cartsRepository;

    /**
     * 添加购物车,将前端穿的数据判断后选择已有的数量还是新增一个购物车商品
     * @param cartsItem
     */
    @Override
    public void addCartItem(CartsItem cartsItem) {
        String id = this.generateId(cartsItem.getSkuId());
        Optional<CartsItem> optional = this.cartsRepository.findById(id);
        if (optional.isPresent()) {
            CartsItem oldItem = optional.get();
            oldItem.setNum(oldItem.getNum()+cartsItem.getNum());
            this.cartsRepository.save(oldItem);

        }else {
            cartsItem.setId(id);
            cartsItem.setUserId(UserContext.getUser().getId());
            this.cartsRepository.save(cartsItem);
        }
    }

    /**
     * 直接查询所有
     * @return
     */
    @Override
    public List<CartsItem> listCartItems() {
        return this.cartsRepository.findByUserId(UserContext.getUser().getId());
    }

    @Override
    public String generateId(Long skuId) {
        Long userId = UserContext.getUser().getId();
        return String.format("u%ds%d", userId, skuId);
    }

    @Override
    public void addCartItems(List<CartsItem> cartsItems) {
        cartsItems.forEach(this::addCartItem);
    }
}
